package com.iplatform.iplatformuser.privilege.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iplatform.iplatformuser.common.CollectionUtil;
import com.iplatform.iplatformuser.common.ConstantUtil;
import com.iplatform.iplatformuser.common.ResponseMsg;
import com.iplatform.commons.pagination.Pagination;
import com.iplatform.iplatformuser.framework.springmvc.BaseController;
import com.iplatform.iplatformuser.framework.util.UniqueIDGenerator;
import com.iplatform.module.privilege.PriMenuBean;
import com.iplatform.module.privilege.PriOrganizationBean;
import com.iplatform.iplatformuser.privilege.service.inter.IPriOrganizationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 组织列表管理接口
 *
 * @author heng
 *
 */
@RestController
@RequestMapping("/api/v1/org")
@Api(tags = "组织列表管理接口")
public class ApiPriOrganizationController extends BaseController {

	@Autowired
	public IPriOrganizationService priOrganizationService;

	@Value("${spring.datasource.driver-class-name}")
	private  String dataSource;

	/**
	 * 组织列表
	 * @param formMap
	 * @param pagination
	 * @return
	 */
	@ApiOperation(value = "组织列表")
	@ApiImplicitParams({
		@ApiImplicitParam(dataType = "String", name = "orgName", value = "名称", required = false, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "orgType", value = "组织机构", required = false, paramType = "query"),
		})
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
		@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public ResponseEntity<PageInfo<PriOrganizationBean>> list(@ApiParam(hidden = true) @RequestParam Map<String, String> formMap,
                                                              @ApiParam(hidden = true) @ModelAttribute(value = "pagination") Pagination pagination) {
		// 默认从最上级查询
		if (StringUtils.isEmpty(formMap.get("orgType"))) {
			formMap.put("orgType", "1");
		}
//
//		PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
//		List<PriOrganizationBean> resultList = priOrganizationService.queryOrganization(formMap);
//		PageInfo<PriOrganizationBean> pageInfo = new PageInfo<PriOrganizationBean>(resultList);
		if("com.mysql.jdbc.Driver".equals(dataSource)) {
			List<PriOrganizationBean> resultList=new ArrayList<>();
			List<PriOrganizationBean> bean = priOrganizationService.queryOrganization(formMap);
			for(PriOrganizationBean test : bean) {
				PriOrganizationBean tmp=new PriOrganizationBean();
				try {
					tmp=(PriOrganizationBean) test.clone();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
				tmp.setChild(null);
				tmp.setOrgLevelName(space(tmp.getOrgLevelName(),tmp.getLevel()));
				resultList.add(tmp);
				getChildList(resultList, test);
			}
			if(formMap.get("orgName")!=null&&formMap.get("orgName")!="") {
				List<PriOrganizationBean> list=new ArrayList<>();
				for (int i = 0; i < resultList.size(); i++) {
					if(resultList.get(i).getOrgName().contains(formMap.get("orgName"))) {
						list.add(resultList.get(i));
					}
				}
				resultList.clear();
				resultList=list;
			}
			if(formMap.get("orgType")!=null&&formMap.get("orgType")!=""&&formMap.get("orgType")!="1") {
				if(formMap.get("orgType") == "2") {
					List<PriOrganizationBean> list=new ArrayList<>();
					for (int i = 0; i < resultList.size(); i++) {
						if(resultList.get(i).getOrgType().equals("201")) {
							list.add(resultList.get(i));
						}
					}
					resultList.clear();
					resultList=list;
				} else if(formMap.get("orgType") == "3") {
					List<PriOrganizationBean> list=new ArrayList<>();
					for (int i = 0; i < resultList.size(); i++) {
						if(resultList.get(i).getOrgType().equals("202")) {
							list.add(resultList.get(i));
						}
					}
					resultList.clear();
					resultList=list;
				} else if(formMap.get("orgType") == "4") {
					List<PriOrganizationBean> list=new ArrayList<>();
					for (int i = 0; i < resultList.size(); i++) {
						if(resultList.get(i).getOrgType().equals("203")) {
							list.add(resultList.get(i));
						}
					}
					resultList.clear();
					resultList=list;
				}
			}
			PageInfo<PriOrganizationBean> pageInfo = new PageInfo<>();
			pageInfo.setTotal(resultList.size());
			pageInfo.setPages(resultList.size()/pagination.getPageSize()+1);
			pageInfo.setPageNum(pagination.getPageNum());
			pageInfo.setPageSize(pagination.getPageSize());
			List<PriOrganizationBean> list=resultList.subList((pagination.getPageNum()-1)*pagination.getPageSize(),
					(pagination.getPageNum()-1)*pagination.getPageSize()+pagination.getPageSize()<resultList.size()?
							(pagination.getPageNum()-1)*pagination.getPageSize()+pagination.getPageSize():resultList.size());
			pageInfo.setList(list);

			return new ResponseEntity<>(pageInfo, HttpStatus.OK);
		}else {
			PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
			List<PriOrganizationBean> resultList = priOrganizationService.queryOrganization(formMap);;

			PageInfo<PriOrganizationBean> pageInfo = new PageInfo<>(resultList);

			pagination.setTotalCount(pageInfo.getTotal());
			pagination.setTotalPageNum(pageInfo.getPages());

			return new ResponseEntity<>(pageInfo, HttpStatus.OK);
		}
	}

	private String space(String name, int level) {
		StringBuilder sb=new StringBuilder();
		for (int i = 1; i < level; i++) {
			sb.append("        ");
		}
		return sb.toString()+name;
	}

	public void getChildList(List<PriOrganizationBean> testList, PriOrganizationBean priOrganizationBean) {
		List<PriOrganizationBean> child = priOrganizationBean.getChild();
		for(PriOrganizationBean chilTest : child) {
			PriOrganizationBean tmp=new PriOrganizationBean();
			try {
				tmp=(PriOrganizationBean) chilTest.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
			tmp.setChild(null);
			tmp.setOrgLevelName(space(tmp.getOrgLevelName(),tmp.getLevel()));
			testList.add(tmp);
			getChildList(testList, chilTest);
		}
	}

	/**
	 * 组织详情
	 *
	 * @param formMap
	 * @return
	 */
	@ApiOperation(value = "组织详情")
	@ApiImplicitParams({
		@ApiImplicitParam(dataType = "String", name = "orgId", value = "ID", required = true, paramType = "path") })
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
		@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@RequestMapping(value = "detail", method = RequestMethod.POST)
	public ResponseEntity<PriOrganizationBean> detail(@ApiParam(hidden = true) @PathVariable Map<String, String> formMap) {

	    if("com.mysql.jdbc.Driver".equals(dataSource)) {
			List<PriOrganizationBean> resultList=new ArrayList<>();
			List<PriOrganizationBean> bean = priOrganizationService.queryOrganization(formMap);
			PriOrganizationBean priorganzationbean =null;
			for(PriOrganizationBean test : bean) {
				PriOrganizationBean tmp=new PriOrganizationBean();
				try {
					tmp=(PriOrganizationBean) test.clone();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
				tmp.setChild(null);
				tmp.setOrgLevelName(space(tmp.getOrgLevelName(),tmp.getLevel()));
				resultList.add(tmp);
				getChildList(resultList, test);

			    if (resultList!=null&&resultList.size()>0) {
			    	priorganzationbean =resultList.get(0);
			    }else {
			    	priorganzationbean = null;
			    }
			}
			return new ResponseEntity<>(priorganzationbean, HttpStatus.OK);
		} else {
				List<PriOrganizationBean> resultList = priOrganizationService.queryOrganization(formMap);
				PriOrganizationBean priorganzationbean =null;
			    if (resultList!=null&&resultList.size()>0) {
			    	priorganzationbean =resultList.get(0);
			    }else {
			    	priorganzationbean = null;
			    }
			    return new ResponseEntity<>(priorganzationbean, HttpStatus.OK);
		}
	}

	/**
	 * 新增组织
	 * @param priOrganizationBean
	 * @return
	 */
	@ApiOperation(value = "新增组织")
	@ApiImplicitParams({
		@ApiImplicitParam(dataType = "String", name = "orgName", value = "名称", required = true, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "orgAbbreviation", value = "简称", required = true, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "parentId", value = "组织父Id", required = true, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "orgType", value = "组织类型Id", required = true, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "remark", value = "描述", required = false, paramType = "query"),
		})
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
		@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public ResponseEntity<ResponseMsg> add(@ApiParam(hidden = true) @ModelAttribute(value = "PriOrganizationBean") PriOrganizationBean priOrganizationBean) {
		if(StringUtils.isEmpty(priOrganizationBean.getRemark())) {
			priOrganizationBean.setRemark("");
		}
		Map<String, String> map = CollectionUtil.getHashMap(1);
		map.put("orgId", priOrganizationBean.getParentId());
		//TODO 获取当前用户
		if("com.mysql.jdbc.Driver".equals(dataSource)) {
			List<PriOrganizationBean> resultList=new ArrayList<>();
			List<PriOrganizationBean> bean = priOrganizationService.queryOrganization(map);
			for(PriOrganizationBean test : bean) {
				PriOrganizationBean tmp=new PriOrganizationBean();
				try {
					tmp=(PriOrganizationBean) test.clone();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
				tmp.setChild(null);
				tmp.setOrgLevelName(space(tmp.getOrgLevelName(),tmp.getLevel()));
				resultList.add(tmp);
				getChildList(resultList, test);
			}
			List<PriOrganizationBean> list=new ArrayList<>();
			for (int i = 0; i < resultList.size(); i++) {
				if(resultList.get(i).getOrgId().equals(map.get("orgId"))) {
					list.add(resultList.get(i));
				}
			}
			resultList.clear();
			resultList=list;
			if (!CollectionUtils.isEmpty(resultList)) {
				priOrganizationBean.setOrgLevel(((PriOrganizationBean) resultList.get(0)).getOrgLevel() + 1);
			} else {
				priOrganizationBean.setOrgLevel(1);
			}

			priOrganizationBean.setOrgId(UniqueIDGenerator.getUUID());
			priOrganizationBean.setCreatedBy("admin");//priManager.getUserCode()

			priOrganizationService.insertOrganization(priOrganizationBean);
			return new ResponseEntity<>(new ResponseMsg(ConstantUtil.SUCCESS), HttpStatus.OK);
		} else {
			List<PriOrganizationBean> parentList = priOrganizationService.queryOrganization(map);
			if (!CollectionUtils.isEmpty(parentList)) {
				priOrganizationBean.setOrgLevel(((PriOrganizationBean) parentList.get(0)).getOrgLevel() + 1);
			} else {
				priOrganizationBean.setOrgLevel(1);
			}

			priOrganizationBean.setOrgId(UniqueIDGenerator.getUUID());
			priOrganizationBean.setCreatedBy("admin");//priManager.getUserCode()

			priOrganizationService.insertOrganization(priOrganizationBean);
			return new ResponseEntity<>(new ResponseMsg(ConstantUtil.SUCCESS), HttpStatus.OK);
		}
	}

	/**
	 * 更新组织
	 * @param priOrganizationBean
	 * @return
	 */
	@ApiOperation(value = "更新组织")
	@ApiImplicitParams({
		@ApiImplicitParam(dataType = "String", name = "orgId", value = "ID", required = true, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "orgName", value = "名称", required = false, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "orgAbbreviation", value = "简称", required = false, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "parentId", value = "组织父Id", required = false, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "orgType", value = "组织类型Id", required = false, paramType = "query"),
		@ApiImplicitParam(dataType = "String", name = "remark", value = "描述", required = false, paramType = "query"),
		})
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
		@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public ResponseEntity<ResponseMsg> update(@ApiParam(hidden = true) @ModelAttribute(value = "PriOrganizationBean")
			PriOrganizationBean priOrganizationBean) {
		if(StringUtils.isEmpty(priOrganizationBean.getRemark())) {
			priOrganizationBean.setRemark("");
		}
		Map<String, String> map = CollectionUtil.getHashMap(1);
		map.put("orgId", priOrganizationBean.getParentId());
		priOrganizationBean.setUpdatedBy("admin");//priManager.getUserCode()
		//TODO 获取当前用户
		if("com.mysql.jdbc.Driver".equals(dataSource)) {
			List<PriOrganizationBean> resultList=new ArrayList<>();
			List<PriOrganizationBean> bean = priOrganizationService.queryOrganization(map);
			for(PriOrganizationBean test : bean) {
				PriOrganizationBean tmp=new PriOrganizationBean();
				try {
					tmp=(PriOrganizationBean) test.clone();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
				tmp.setChild(null);
				tmp.setOrgLevelName(space(tmp.getOrgLevelName(),tmp.getLevel()));
				resultList.add(tmp);
				getChildList(resultList, test);
			}
			List<PriOrganizationBean> list=new ArrayList<>();
			for (int i = 0; i < resultList.size(); i++) {
				if(resultList.get(i).getOrgId().equals(map.get("orgId"))) {
					list.add(resultList.get(i));
				}
			}
			resultList.clear();
			resultList=list;
			if (!CollectionUtils.isEmpty(resultList)) {
				priOrganizationBean.setOrgLevel(((PriOrganizationBean) resultList.get(0)).getOrgLevel() + 1);
			} else {
				priOrganizationBean.setOrgLevel(1);
			}

			priOrganizationService.updateOrganization(priOrganizationBean);
			return new ResponseEntity<>(new ResponseMsg(ConstantUtil.SUCCESS), HttpStatus.OK);
		} else {
			List<PriOrganizationBean> parentList = priOrganizationService.queryOrganization(map);
			if (!CollectionUtils.isEmpty(parentList)) {
				priOrganizationBean.setOrgLevel(((PriOrganizationBean) parentList.get(0)).getOrgLevel() + 1);
			} else {
				priOrganizationBean.setOrgLevel(1);
			}

			priOrganizationService.updateOrganization(priOrganizationBean);
			return new ResponseEntity<>(new ResponseMsg(ConstantUtil.SUCCESS), HttpStatus.OK);
		}
	}

	/**
	 * 删除组织
	 * @param deleteIds
	 * @return
	 */
	@ApiOperation(value = "删除组织")
	@ApiImplicitParams({
		@ApiImplicitParam(dataType = "String", name = "deleteIds", value = "删除的ID，逗号分隔", required = true, paramType = "query") })
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
		@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@RequestMapping(value = "del", method = RequestMethod.POST)
	public ResponseEntity<ResponseMsg> del(@RequestParam String deleteIds) {

		priOrganizationService.batchDelete(deleteIds.split(","));

		return new ResponseEntity<>(new ResponseMsg(ConstantUtil.SUCCESS), HttpStatus.OK);
	}



	/**
	 * 组织新增和编辑页面上级下拉框
	 *
	 * @param formMap
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "组织新增和编辑页面上级下拉框")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
		@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@RequestMapping(value = "/selectedOrgs", method = RequestMethod.POST)
	public ResponseEntity<List<PriOrganizationBean>> selectedOrgs(@ApiParam(hidden = true) @RequestParam Map<String, String> formMap) {
		if("com.mysql.jdbc.Driver".equals(dataSource)) {
			List<PriOrganizationBean> resultList=new ArrayList<>();
			List<PriOrganizationBean> bean = priOrganizationService.queryOrganization(formMap);
			for(PriOrganizationBean test : bean) {
				PriOrganizationBean tmp=new PriOrganizationBean();
				try {
					tmp=(PriOrganizationBean) test.clone();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
				tmp.setChild(null);
				tmp.setOrgLevelName(space(tmp.getOrgLevelName(),tmp.getLevel()));
				resultList.add(tmp);
				getChildList(resultList, test);
			}
			return new ResponseEntity<>(resultList, HttpStatus.OK);
		} else {
			List<PriOrganizationBean> orgtList = priOrganizationService.queryOrganization(formMap);
			return new ResponseEntity<>(orgtList, HttpStatus.OK);
		}

	}


	/**
	 * 查询组织名称
	 * @param formMap
	 * @param pagination
	 * @return
	 */
	@ApiOperation(value = "查询组织名称")
	@RequestMapping(value = "/queryOrgNameList", method = RequestMethod.POST)
	public ResponseEntity<JSONObject> queryOrgNameList() {

		List<Map<String, String>> resultList = priOrganizationService.queryOrgName();

		JSONObject allObject = new JSONObject();
		JSONArray arrayName = new JSONArray();

		for(Map<String, String> nameList : resultList) {
			JSONObject objectName = new JSONObject();
			objectName.put("orgName", nameList.get("orgName"));
			arrayName.add(objectName);
		}
		allObject.put("name", arrayName);
		return new ResponseEntity<>(allObject, HttpStatus.OK);
	}
	
	
	
	@ApiOperation(value = "查询组织机构列表")
	@ResponseBody
	@GetMapping(value = "/queryOrgList")
	public ResponseEntity<List<PriOrganizationBean>> queryOrgList() {
		List<PriOrganizationBean> organizationList = priOrganizationService.queryOrgList();
		return new ResponseEntity<>(organizationList, HttpStatus.OK);
	}
	
}
